package controller

import (
	"log"
	"user-agent/database/bean"
	"user-agent/database/schema"

	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
)

type userAgentCtrl struct{}

var UserAgent = &userAgentCtrl{}

var model = &bean.UserAgentBean{}

func (ctrl *userAgentCtrl) Post(ctx context.Context) {
	form := schema.UserAgent{}
	ctx.ReadJSON(&form)
	form.Agent = ctx.GetHeader("user-agent")
	if err := model.Insert(&form); err != nil {
		ctx.StatusCode(iris.StatusServiceUnavailable)
		log.Println(err)
		return
	}
	ctx.StatusCode(iris.StatusOK)
	ctx.JSON(form)
}

func (ctrl *userAgentCtrl) Get(ctx context.Context) {
	list, err := model.GetAll()
	if err != nil {
		log.Println(err)
		ctx.StatusCode(iris.StatusServiceUnavailable)
	} else {
		ctx.JSON(list)
	}
}
